<!--  -->
<template>
  <el-dialog
    v-model="showAllRole"
    title="分配角色"
    width="30%"
    :before-close="() => cancel()"
  >
    <el-form :model="form">
      <el-select
        v-model="form.selectRoles"
        fit-input-width
        multiple
        filterable
        default-first-option
        placeholder="请选择"
      >
        <el-option
          v-for="item in roleListRef"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="() => cancel()">取消</el-button>
        <el-button type="primary" @click="updateRoles">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, toRefs, ref, Ref, watch } from "vue";
import * as http from "../../../request/http";
// 下拉框

let props = defineProps<{
  showAllRole: boolean;
  aid: number;
}>();

// 点击取消
// 子传父
let emit = defineEmits<{
  (event: "hiddenRole", flag?: string): void;
}>();
function cancel(flag?: string) {
  emit("hiddenRole", flag);
}
// 点击确定
async function updateRoles() {
  let res = await http.updateAdminRole({
    adminId: props.aid,
    roleIds: form.value.selectRoles.join(","),
  });
  if (res.code === 200) {
    cancel("reloadRoles");
  }

  // console.log("fghk", form.value.selectRoles);
  // console.log(form.value.selectRoles.(","));
}

// 请求接口 获取用户角色
let form = ref({
  selectRoles: [] as number[],
});

let roleListRef = ref([]) as Ref<RoleObjRes[]>;
async function fetchRole() {
  let res = await http.getRoleListAll();
  if (res.code === 200) {
    roleListRef.value = res.data;
    console.log(res);
  }
}
fetchRole();

// 监听aid变化 来更新 当前角色
watch(
  () => props.aid,
  async (newVal, oldVal) => {
    if (newVal) {
      let res = await http.getRoleById(newVal);
      if (res.code === 200) {
        form.value.selectRoles = res.data.map((item) => item.id);
        // console.log(form.value.selectRoles.join(","));
      }
    }
  }
);
</script>
<style lang="less" scoped></style>
